const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

// 验证管理员token
async function verifyAdminToken(token) {
  try {
    const result = await db.collection('admin_tokens').where({
      token: token,
      expireTime: _.gt(new Date())
    }).get()
    
    if (result.data.length > 0) {
      await db.collection('admin_tokens').doc(result.data[0]._id).update({
        data: { lastUsed: new Date() }
      })
      return true
    }
    return false
  } catch (error) {
    console.error('验证管理员token错误:', error)
    return false
  }
}

exports.main = async (event, context) => {
  const { action, adminToken, page = 1, limit = 20, search = '', activityId, activityData } = event
  
  console.log('活动管理操作:', { action, page, limit, search, activityId })
  
  // 验证管理员权限
  if (!await verifyAdminToken(adminToken)) {
    return { 
      success: false, 
      message: '权限不足或登录已过期，请重新登录' 
    }
  }
  
  try {
    switch (action) {
      case 'list':
        // 获取活动列表
        let query = db.collection('activities')
        
        // 搜索条件
        if (search) {
          query = query.where({
            title: db.regExp({
              regexp: search,
              options: 'i'
            })
          })
        }
        
        // 获取总数
        const countResult = await query.count()
        const total = countResult.total
        
        // 获取分页数据
        const activities = await query
          .skip((page - 1) * limit)
          .limit(limit)
          .orderBy('createTime', 'desc')
          .get()
        
        // 映射字段为前端期望的格式
        const activitiesMapped = activities.data.map(activity => ({
          _id: activity._id,
          coverImage: activity.bannerImage || '',
          title: activity.eventName || '',
          eventTitle: activity.eventTitle || '',
          participantCount: activity.signedUpCount || 0,
          maxParticipants: activity.maxParticipants || 0,
          startTime: activity.startTime || '',
          endTime: activity.endTime || '',
          location: activity.location || '',
          status: activity.status || '报名中',
          recommended: activity.recommended || 0,
          price: activity.price || 0,
          createTime: activity.createTime || '',
          updateTime: activity.updateTime || ''
        }))
        
        console.log('获取活动列表成功:', { total, count: activitiesMapped.length })
        
        return {
          success: true,
          data: activitiesMapped,
          total: total,
          page: page,
          limit: limit
        }
        
      case 'create':
        // 创建活动
        if (!activityData) {
          return { success: false, message: '活动数据不能为空' }
        }
        
        const newActivity = {
          bannerImage: activityData.coverImage || '',
          eventName: activityData.title || '',
          eventTitle: activityData.eventTitle || '',
          type: activityData.type || '',
          description: activityData.description || '',
          startTime: activityData.startTime || '',
          endTime: activityData.endTime || '',
          location: activityData.location || '',
          maxParticipants: activityData.maxParticipants || 100,
          signedUpCount: 0,
          recommended: activityData.recommended || 0,
          price: activityData.price || 0,
          status: activityData.status === 'pending' ? '报名中' : 
                  activityData.status === 'active' ? '进行中' : 
                  activityData.status === 'ended' ? '已结束' : '已取消',
          createTime: new Date(),
          updateTime: new Date()
        }
        
        const createResult = await db.collection('activities').add({
          data: newActivity
        })
        
        console.log('活动创建成功:', { activityId: createResult._id })
        return { 
          success: true, 
          message: '活动创建成功',
          activityId: createResult._id
        }
        
      case 'update':
        // 更新活动
        if (!activityId || !activityData) {
          return { success: false, message: '参数不完整' }
        }
        
        const updateData = {
          bannerImage: activityData.coverImage,
          eventName: activityData.title,
          eventTitle: activityData.eventTitle,
          type: activityData.type,
          description: activityData.description,
          startTime: activityData.startTime,
          endTime: activityData.endTime,
          location: activityData.location,
          maxParticipants: activityData.maxParticipants,
          recommended: activityData.recommended,
          price: activityData.price,
          status: activityData.status === 'pending' ? '报名中' : 
                  activityData.status === 'active' ? '进行中' : 
                  activityData.status === 'ended' ? '已结束' : '已取消',
          updateTime: new Date()
        }
        
        await db.collection('activities').doc(activityId).update({
          data: updateData
        })
        
        console.log('活动更新成功:', { activityId })
        return { success: true, message: '活动更新成功' }
        
      case 'delete':
        // 删除活动
        if (!activityId) {
          return { success: false, message: '活动ID不能为空' }
        }
        
        // 检查是否有报名记录
        const registrationCount = await db.collection('activity_registrations')
          .where({
            activityId: activityId
          })
          .count()
        
        if (registrationCount.total > 0) {
          return { 
            success: false, 
            message: '该活动已有用户报名，无法删除' 
          }
        }
        
        await db.collection('activities').doc(activityId).remove()
        
        console.log('活动删除成功:', { activityId })
        return { success: true, message: '活动删除成功' }
        
      case 'changeStatus':
        // 修改活动状态
        if (!activityId || !activityData.status) {
          return { success: false, message: '参数不完整' }
        }
        
        // 将英文状态映射为汉字
        let statusText = activityData.status
        if (activityData.status === 'pending') statusText = '报名中'
        else if (activityData.status === 'active') statusText = '进行中'
        else if (activityData.status === 'ended') statusText = '已结束'
        else if (activityData.status === 'cancelled') statusText = '已取消'
        
        await db.collection('activities').doc(activityId).update({
          data: { 
            status: statusText,
            updateTime: new Date()
          }
        })
        
        console.log('活动状态修改成功:', { activityId, status: activityData.status })
        return { success: true, message: '活动状态修改成功' }
        
      case 'getRegistrations':
        // 获取活动报名列表
        if (!activityId) {
          return { success: false, message: '活动ID不能为空' }
        }
        
        const registrations = await db.collection('activity_registrations')
          .where({
            activityId: activityId
          })
          .orderBy('registrationTime', 'desc')
          .get()
        
        // 获取用户信息
        const registrationsWithUser = await Promise.all(
          registrations.data.map(async (registration) => {
            const userResult = await db.collection('users')
              .doc(registration.userId)
              .get()
            
            return {
              ...registration,
              userInfo: userResult.data || {}
            }
          })
        )
        
        return {
          success: true,
          data: registrationsWithUser
        }
        
      default:
        return { success: false, message: '无效的操作类型' }
    }
  } catch (error) {
    console.error('活动管理操作错误:', error)
    return { 
      success: false, 
      error: error.message,
      message: '操作失败，请稍后重试'
    }
  }
}